package com.sphd.emanu.activity.changepwd;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.login.LoginActivity;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.login.User;
import com.wzutils.JsonUtil;
import com.wzutils.MD5Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * todo 修改密码 忘记密码共用界面
 *
 * @Author Hu
 * @Time 2017/7/26 -- 8:36.
 * @Email 87683202@qq.com
 */
public class ChangePwdActivity extends MVPBaseActivity<ChangePwdContract.View, ChangePwdPresenter> implements ChangePwdContract.View, Handler.Callback {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_phone)
    MaterialEditText userPhone;
    @BindView(R.id.user_pwd)
    MaterialEditText userPwd;
    @BindView(R.id.user_vercode)
    MaterialEditText userVercode;
    @BindView(R.id.btn_get_code)
    Button btnGetCode;
    @BindView(R.id.btn_finish)
    Button btnFinish;
    boolean isChange = false;
    Intent intent;
    Bundle bundle;
    AndroidNextInputs inputs;
    User user;
    @BindView(R.id.layout_vercode)
    LinearLayout layoutVercode;
    private boolean ready;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_pwd);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> {
            finish();
        });
    }

    private void initView() {
        inputs = new AndroidNextInputs();
        intent = getIntent();
        bundle = intent.getExtras();
        isChange = bundle.getBoolean(Constant.CHANGE_PWD);
        if (isChange) {
            user = (User) bundle.getSerializable(Constant.USER_ENTITY);
            userPhone.setText(user.getLogonname());
            userPhone.setEnabled(false);
            userPhone.setShowClearButton(false);
            toolbar.setSubtitle(user.getLogonname());
            setTitleBar(toolbar, "修改密码");
        } else {
            setTitleBar(toolbar, "忘记密码");
        }
        initSdk();
    }

    private void initSdk() {
        if (Build.VERSION.SDK_INT >= 23) {
            int readPhone = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            int receiveSms = checkSelfPermission(Manifest.permission.RECEIVE_SMS);
            int readSms = checkSelfPermission(Manifest.permission.READ_SMS);
            int readContacts = checkSelfPermission(Manifest.permission.READ_CONTACTS);
            int readSdcard = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

            int requestCode = 0;
            ArrayList<String> permissions = new ArrayList<String>();
            if (readPhone != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 0;
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (receiveSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 1;
                permissions.add(Manifest.permission.RECEIVE_SMS);
            }
            if (readSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 2;
                permissions.add(Manifest.permission.READ_SMS);
            }
            if (readContacts != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 3;
                permissions.add(Manifest.permission.READ_CONTACTS);
            }
            if (readSdcard != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 4;
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (requestCode > 0) {
                String[] permission = new String[permissions.size()];
                this.requestPermissions(permissions.toArray(permission), requestCode);
                return;
            }
        }
        registerSDK();
    }

    private void registerSDK() {
        // 在尝试读取通信录时以弹窗提示用户（可选功能）
        SMSSDK.setAskPermisionOnReadContact(true);
        final Handler handler = new Handler(this);
        EventHandler eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        registerSDK();
    }

    @OnClick({R.id.btn_get_code, R.id.btn_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_get_code:
                inputs.clear();
                inputs.add(userPhone, StaticScheme.Required(), StaticScheme.NotBlank(), StaticScheme.ChineseMobile());
                if (inputs.test()) {
                    SMSSDK.getVerificationCode("86", userPhone.getText().toString().trim());
                    toast("已发送");
                } else {
                    toast("请按提示要求填写");
                }
                break;
            case R.id.btn_finish:

                inputs.clear();
                if (ready) {
                    inputs.add(userPhone, StaticScheme.Required(), StaticScheme.NotBlank(), StaticScheme.ChineseMobile()).add(userPwd,
                            StaticScheme.Required(), StaticScheme.NotBlank());
                    if (inputs.test()) {
                        addData();
                    } else {
                        toast("请按提示要求填写");
                    }
                } else {
                    inputs.add(userPhone, StaticScheme.Required(), StaticScheme.NotBlank(), StaticScheme.ChineseMobile()).add(userPwd, StaticScheme.Required(), StaticScheme.NotBlank())
                            .add(userVercode, StaticScheme.Required(), StaticScheme.NotBlank(), StaticScheme.Numeric());
                    if (inputs.test()) {
                        SMSSDK.submitVerificationCode("86",
                                userPhone.getText().toString().trim(), userVercode.getText().toString().trim());
                    } else {
                        toast("请按提示要求填写");
                    }
                }


                break;
        }
    }

    private void addData() {
        showProgressDialog();
        mPresenter.updatePassword(userPhone.getText().toString().trim(), MD5Utils.MD5(userPwd.getText().toString().trim()));
    }

    @Override
    public boolean handleMessage(Message msg) {

        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        if (result == SMSSDK.RESULT_COMPLETE) {
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                addData();
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                boolean smart = (Boolean) data;
                if (smart) {
                    //通过智能验证
                    toast("您已通过智能验证，无需再次输入验证码。");
                    layoutVercode.setVisibility(View.GONE);
                    ready = true;
                } else {
                    //依然走短信验证
                    ready = false;
                    layoutVercode.setVisibility(View.VISIBLE);
                }
            }
        } else if (result == SMSSDK.RESULT_ERROR) {
            ((Throwable) data).printStackTrace();
            Log.e("data", data.toString());
            toast(JsonUtil.getJsonObject(((Throwable) data).getMessage()).getString("detail"));
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        if (ready) {
            // 销毁回调监听接口
            SMSSDK.unregisterAllEventHandler();
        }
        super.onDestroy();

    }

    @Override
    public void setRes(int res) {
        //返回值,-1为帐号已存在,0为新增失败,1为成功
        dissProgressDialog();
        if (res == 1) {
            toast("操作成功。");

            intent.putExtra(Constant.LOGIN_NAME, userPhone.getText().toString().trim());
            intent.putExtra(Constant.LOGIN_PWD, userPwd.getText().toString().trim());
            intent.putExtra(Constant.CHANGE_PWD, true);
            intent.setClass(context, LoginActivity.class);
            startActivity(intent);
            finish();
        } else if (res == -1) {
            toast("帐号不存在");
        } else if (res == 0) {
            toast("操作失败，请重试！");
        }
    }
}
